package com.btex.app;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.btex.app.entity.HeYueEventBusInfo;
import com.btex.app.pager.FragmentAdapter;
import com.btex.app.pager.MyLazyPager;
import com.btex.app.tools.CookieTool;
import com.btex.app.tools.SharedPreferencesUtil;
import com.btex.app.tools.Util;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.util.PreferencesCookieStore;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class TabsActivity extends FragmentActivity implements RadioGroup.OnCheckedChangeListener, View.OnClickListener {
    private static final String TAG = "TabsActivity";
    public static MyLazyPager layout_content;
    private FragmentAdapter fragmentAdapter;
    private RadioGroup tab_radio;
    private String token;
    private SharedPreferencesUtil sp;
    private TextView tv_title;
    private TextView tv_menu;
    public PreferencesCookieStore cookieStore;
    private Context cxt;
    private RelativeLayout mRl_title;

    public boolean isOne = true;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tabs);

        hideBottomUIMenu();

//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
//        if (!isTaskRoot()) {
//            finish();
//            return;
//        }
        EventBus.getDefault().register(this);
        sp = SharedPreferencesUtil.getSharedPreferences(this);
        cxt = this;
        token = sp.getString(Config.TOKEN, null);
        cookieStore = CookieTool.getCookieStore(this, sp);
        getSession();
        initView();
        setData();


    }


    public void getSession() {


        int num = (int) ((Math.random() * 9 + 1) * 30000);


        final HttpUtils http = new HttpUtils();
        RequestParams params = new RequestParams();

        http.send(HttpRequest.HttpMethod.GET, Config.URL_ADVERT_ONE + "?rnd=" + String.valueOf(num), params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                String result = responseInfo.result.toString();
                try {
                    JSONObject jsonObject = new JSONObject(result);

                    String data = jsonObject.getString(Config.KEY_CODE);

                    if ("1".equals(data)) {
                        isOne = true;
                    }
//                    getIPInfo();


                } catch (Exception e) {
                    isOne = false;
//                    getIPInfo();
                    e.printStackTrace();

                }

            }

            @Override
            public void onFailure(HttpException error, String msg) {
                isOne = false;
//                getIPInfo();

            }
        });
    }

    private void getIPInfo() {

        int num = (int) ((Math.random() * 9 + 1) * 100000);
        OkGo.<String>get("https://raw.githubusercontent.com/btex-dev/btex-api-demos/master/domains?" + "rnd=" + String.valueOf(num)).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String result = response.body().toString();

                JSONArray array = null;
                try {
                    array = new JSONArray(result);
                } catch (Exception e) {
                    e.printStackTrace();

                }

                try {

                    //将字符串转成json数组
                    for (int i = 0; i < array.length(); i++) {
                        String b0 = null;
                        try {
                            b0 = array.getString(i);
                        } catch (JSONException e) {
                            e.printStackTrace();

                        }

                        if (isOne) {
                            if (i == 0) {
                                Config config = new Config();
                                config.setBase(b0);
                            }

                        } else {
                            if (i == 1) {
                                Config config = new Config();
                                config.setBase(b0);
                            }
                        }
                    }

                } catch (Exception e) {

                }

            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);

            }
        });
    }

    private void hideBottomUIMenu() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().getDecorView().setFitsSystemWindows(true);

        }
    }


    public void initView() {
        mRl_title = (RelativeLayout) findViewById(R.id.rl_title);
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_menu = (TextView) findViewById(R.id.tv_menu);
        findViewById(R.id.iv_back).setVisibility(View.GONE);
        layout_content = (MyLazyPager) findViewById(R.id.layout_content);
        fragmentAdapter = new FragmentAdapter(getSupportFragmentManager());
        tab_radio = (RadioGroup) findViewById(R.id.tab_radio);
        tab_radio.setOnCheckedChangeListener(this);

        layout_content.setAdapter(fragmentAdapter);
        layout_content.setOffscreenPageLimit(5);

        ((RadioButton) tab_radio.getChildAt(getIntent().getIntExtra("page", 0))).setChecked(true);

        mRl_title.setVisibility(View.GONE);

        tv_menu.setOnClickListener(this);

    }

    public void setData() {
//        MobclickAgent.onPause(this);
    }

    @Override
    protected void onResume() {
        super.onResume();


//        MobclickAgent.onResume(this);
        String check = sp.getString("check", "0");

        Integer integer = Integer.valueOf(check);

        if (layout_content != null) {

            ((RadioButton) tab_radio.getChildAt(integer)).setChecked(true);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();

    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {

            case R.id.rb_tab1:
                Log.i("oiqwjdqoiwdjoqjwd", "2");
                sp.putString("check", "0");
                layout_content.setCurrentItem(Config.TAB_FRAGMENT1, false);
                mRl_title.setVisibility(View.GONE);
                sp.putBoolean("istab2", false);

                break;
            case R.id.rb_tab2:
                Log.i("oiqwjdqoiwdjoqjwd", "3");
                sp.putString("check", "1");
                mRl_title.setVisibility(View.VISIBLE);
                mRl_title.setBackgroundResource(R.color.white);
                layout_content.setCurrentItem(Config.TAB_FRAGMENT2, false);
                tv_title.setTextColor(getResources().getColor(R.color.black));
                tv_title.setText(getString(R.string.tab_name2));
                sp.putBoolean("istab2", true);
                break;
            case R.id.rb_tab3:
                mRl_title.setBackgroundResource(R.color.kine_tv_new);

                String check = sp.getString("check", "");
                if (!"".equals(check)) {

                }
                boolean aBoolean = sp.getBoolean(Config.KEY_IS_LOGIN, false);
                if (aBoolean) {
                    sp.putString("check", "3");
                    mRl_title.setVisibility(View.GONE);
                    layout_content.setCurrentItem(Config.TAB_FRAGMENT3, false);
                    tv_title.setText(getString(R.string.tab_name3));
                    sp.putBoolean("istab2", false);
                } else {
                    Intent intent = new Intent(this, LoginActivity.class);
                    startActivity(intent);

                }
                break;

            case R.id.rb_tab4:

                sp.putString("check", "4");
                mRl_title.setVisibility(View.VISIBLE);
                mRl_title.setBackgroundResource(R.color.kine_tv_new);

                if (sp.getBoolean(Config.KEY_IS_LOGIN, false))
                    layout_content.setCurrentItem(Config.TAB_FRAGMENT4, false);
                else {
//                    tv_menu.setText(getString(R.string.regist));
                    layout_content.setCurrentItem(Config.TAB_FRAGMENT5, false);
                }
                tv_title.setTextColor(getResources().getColor(R.color.white));
                tv_title.setText(getString(R.string.tab_name4));
                sp.putBoolean("istab2", false);
                break;

            case R.id.rb_tab5:
//                新增
//                mRl_title.setVisibility(View.GONE);
//                sp.putString("check", "2");
//                tv_title.setText(getString(R.string.heyue_tab));
//                layout_content.setCurrentItem(Config.TAB_COUNT_heyue, false);
//                sp.putBoolean("istab2", false);

                break;

        }
    }

    long exitTime = 0;

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {

        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
//                Toast.makeText(TabsActivity.this, "再按一次退出BTEX", Toast.LENGTH_SHORT).show();
                boolean isEngilsh = sp.getBoolean("isEngilsh", false);
                if (isEngilsh) {
                    Util.showSnachBar(TabsActivity.this, getResources().getColor(R.color.red), "Tap again to exit");
                } else {
                    Util.showSnachBar(TabsActivity.this, getResources().getColor(R.color.red), "再按一次退出BTEX");
                }
                exitTime = System.currentTimeMillis();
            } else {
                sp.putString("check", "0");
                System.exit(0);
                finish();
            }
            return true;
        }
        return super.dispatchKeyEvent(event);
    }


    @Override
    public void onClick(View v) {
        Intent i;
        switch (v.getId()) {
            case R.id.tv_menu:
                String text = tv_menu.getText().toString();
                if (getString(R.string.login).equals(text)) {
                    ((RadioButton) (tab_radio.getChildAt(3))).setChecked(true);
                    layout_content.setCurrentItem(Config.TAB_FRAGMENT5, false);
                    tv_title.setText(getString(R.string.login));
                } else {
                    i = new Intent(cxt, RegistActivity.class);
                    startActivity(i);
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        sp.putString(Config.TOKEN,null);
        sp.putString("check", "0");
        EventBus.getDefault().unregister(this);

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void messageEventBus(String event) {

        if ("killActivity".equals(event)) {
            finish();
        }

        if ("TabsActivity1".equals(event)) {
            sp.putString("check", "0");
            ((RadioButton) tab_radio.getChildAt(0)).setChecked(true);
        }

        if (event.equals("loginsuccess")) {
            sp.putString("check", "0");
            ((RadioButton) tab_radio.getChildAt(0)).setChecked(true);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void TreatyFragment(HeYueEventBusInfo event) {
        ((RadioButton) tab_radio.getChildAt(2)).setChecked(true);
        mRl_title.setVisibility(View.GONE);
        sp.putString("check", "2");
        tv_title.setText("合约");

        layout_content.setCurrentItem(Config.TAB_COUNT_heyue, false);
        sp.putBoolean("istab2", false);


    }


}
